/**
 * api
 */
// import fetch from 'isomorphic-fetch';
// import fetchJsonp from 'fetch-jsonp';
import axios from 'axios';
import { isObjEmpty } from './tool';
import STATUS_CODE from './status_code';

const URLS = {
  'chance-type': '/chance-type',
  'user-list': '/user-list',
};

const customHeader = {
  Accept: 'application/json',
  'X-Requested-With': 'XMLHttpRequest',
  'Content-Type': 'application/json;charset=UTF-8',
};

/**
 * axios请求
 * @param  {String} path   请求路径
 * @param  {Object} data   请求参数
 * @param  {String} method 请求类型
 * @param  {Object} opts   请求选项
 * @return {Object}        Promise对象
 */
function axiosPost(action, data, method, opts) {
  const path = URLS[action];
  if (!path) return Promise.reject(new Error('无效的API地址'));
  const option = {
    method: method ? method.toLowerCase() : 'get',
    credentials: 'include',
    headers: customHeader,
  };
  if (!isObjEmpty(data)) {
    option.params = data;
  }
  return axios(path, { ...option, ...opts }).then((res) => {
    if (res.status !== STATUS_CODE.SUCCESS) return Promise.reject(new Error(res.msg));
    return Promise.resolve(res.data);
  });
}

export { axiosPost as fetch };
